package com.yu.newsSys.filter;

import com.yu.newsSys.constants.SessionConstants;
import com.yu.newsSys.utils.CommonUtils;
import com.yu.newsSys.vo.Result;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
        // 定义黑名单
        String[] blackList = {"/add.html", "/main.html", "/edit.html", "/news"};
        // 定义标志位 false表示不需要拦截
        boolean flag = false;
        // 判断是否需要拦截
        for (String black : blackList) {
            if (uri.contains(black)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            System.out.println(uri + "已被拦截");
            // 获取session判断用户是否已经登录
            String user = (String) req.getSession().getAttribute(SessionConstants.USER_SESSION);
            if (user == null) {
                // 未登录 则判断是同步请求还是异步请求 若是异步请求，无法直接使用重定向跳转到 login.html
                if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                    // 异步请求
                    System.out.println(uri + "为非法异步请求 已为您重定向");

                    Result result = Result.ERROR(302, "未登录");
                    CommonUtils.printData(result, resp);
                } else {
                    // 同步请求
                    System.out.println(uri + "为非法同步请求 已为您重定向");
                    resp.sendRedirect(req.getContextPath() + "/login.html");
                }
            } else {
                // 已登录 直接放行
                System.out.println("用户已登录" + uri + "已放行");
                filterChain.doFilter(req, resp);

            }
        } else {
            System.out.println("资源为公有" + uri + "已放行");
            filterChain.doFilter(req, resp);
        }

    }
}
